<template>
  <div class="container mt-5 d-flex gap-3 flex-wrap">
    <ul class="list-group">
      <li class="list-group-item">Назва: {{calculator.name}}</li>
      <li class="list-group-item">Кредит: {{calculator.initial_loan}} $</li>
      <li class="list-group-item">Аванс: {{calculator.down_payment}} $</li>
      <li class="list-group-item">Ставка: {{bank.rate}} %</li>
      <li class="list-group-item">Термін: {{calculator.term}} місяців</li>
    </ul>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Щомісячний платіж</h5>
        <p class="card-text">{{monthlyPayment}}</p>
      </div>
      <div class="card-body">
        <h5 class="card-title">Місячна ставка</h5>
        <p class="card-text">{{monthlyRate}}</p>
      </div>
    </div>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Нараховано відсотків</h5>
        <p class="card-text">{{accruedInterest}}</p>
      </div>
      <div class="card-body">
        <h5 class="card-title">Загальна сума</h5>
        <p class="card-text">{{fullAmount}}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: [
    'calculatorId'
  ],
  data() {
    return {
      calculator: {},
      bank: {}
    }
  },
  computed: {
    balanceOfDebt () {
      return this.calculator.initial_loan - this.calculator.down_payment
    },
    monthlyRate() {
      const rate = this.bank.rate
      return rate/(100*12)
    },
    monthlyPayment() {
      // СЗ*(П+(П/(1+П)*СК-1))
      const debt = this.balanceOfDebt
      const rate = this.monthlyRate
      const term = this.calculator.term
      const mpaym = debt*(rate/(1-(1+rate)**((term-1)*-1)))
      return Math.ceil(mpaym)
    },
    fullAmount() {
      const term = this.calculator.term
      return this.monthlyPayment*term
    },
    accruedInterest () {
      return this.fullAmount-this.balanceOfDebt
    }

  },
  methods: {
    getCalculator() {
      axios.get('/api/v1/calculators/'+this.calculatorId)
        .then(response => {
          this.calculator = response.data.data
        })
        .catch(error => {
          console.error(error)
          this.errored = true
        })
        .finally(() => {
          this.getBank()
        })
    },
    getBank() {
      axios.get('/api/v1/banks/'+this.calculator.bank_id)
        .then(response => {
          this.bank = response.data.data
        })
        .catch(error => {
          console.error(error)
          this.errored = true
        })
        .finally(() => {
          this.loading = false
        })
    }
  },
  created() {
    this.getCalculator()
  },
}
</script>

<style>

</style>